<template>
	<view class="addProject f18">
		<uni-forms ref="baseForm" :modelValue="formData">
			<uni-forms-item label="名称" required>
				<uni-easyinput isLoading v-model="formData.projectName" placeholder="请输入名称" />
			</uni-forms-item>
			<uni-forms-item label="联系手机" required>
				<uni-easyinput :disabled="isLoading" type="number" v-model="formData.connectPublisher"
					placeholder="请输入联系方式" />
			</uni-forms-item>
			<uni-forms-item label="报名时间" required>
				<uni-datetime-picker v-model="reportrange" type="daterange" @change="reportchange" />
			</uni-forms-item>
			<uni-forms-item label="举办时间" required>
				<uni-datetime-picker type="daterange" v-model="startrange" @change="startchange" />
			</uni-forms-item>
			<uni-forms-item label="类型" required>
				<uni-data-checkbox v-model="formData.instituteType" :localdata="type" />
			</uni-forms-item>
			<uni-forms-item label="地点" required>
				<uni-easyinput v-model="formData.place" :disabled="isLoading" placeholder="请输入地点" />
			</uni-forms-item>
			<uni-forms-item label="发起组织" required>
				<uni-data-picker class="w100" placeholder="请选择发起组织" popup-title="请选择学院" :localdata="dataTree"
					v-model="formData.createDepartment" @change="onchange"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="比赛简介" required>
				<uni-easyinput type="textarea" :disabled="isLoading" v-model="formData.briefly" placeholder="请输入比赛简介" />
			</uni-forms-item>
			<uni-forms-item label="比赛内容" required>
				<uni-easyinput type="textarea" :disabled="isLoading" v-model="formData.content" placeholder="请输入比赛内容" />
			</uni-forms-item>

			<uni-forms-item label="规则" required>
				<uni-easyinput type="textarea" :disabled="isLoading" v-model="formData.rule" placeholder="请输入规则" />
			</uni-forms-item>
			<uni-forms-item label="奖励" required>
				<uni-easyinput type="textarea" :disabled="isLoading" v-model="formData.reward" placeholder="请输入奖励" />
			</uni-forms-item>
			<uni-forms-item label="加入方式" required>
				<uni-easyinput type="textarea" :disabled="isLoading" v-model="formData.enterWay"
					placeholder="请输入加入方式" />
			</uni-forms-item>
			<!-- reload判断是否回显进来动态渲染组件 -->
			<uni-forms-item label="图片上传" v-if="!reload">
				<view class="example-body">
					<uni-file-picker v-if="!isUploadSomeError" v-model="imageValue" fileMediatype="image" mode="grid"
						@select="select" @progress="progress" @success="success" @fail="fail" limit="9"
						title="最多选择9张图片">
					</uni-file-picker>
					<view class="fileUpload" v-else>
						<view class="color-red">以下图片上传失败，请点击重传</view>
						<view class="fileUploadList">
							<template v-for="(item,index) in fileerrorList">
								<view :key="item.path" class="errUploadImage" @click="reloadUpload(index)">
									<image :src="item.path"></image>
								</view>
							</template>
						</view>

					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item label="图片上传" v-else>
				<view class="example-body">
					<!-- 回显进来，先判断是否有图片记录，有的话自己遍历上传，没有的话按照uniapp组件上传 -->
					<view>
						<view class="example-body" v-if="!isReloadHaveImg">
							<uni-file-picker v-if="!isUploadSomeError" v-model="imageValue" fileMediatype="image"
								mode="grid" @select="select" @fail="fail" limit="9" title="最多选择9张图片" delIcon="false">
							</uni-file-picker>
							<view class="fileUpload" v-else>
								<view class="color-red">以下图片上传失败，请点击重传</view>
								<view class="fileUploadList">
									<template v-for="(item,index) in fileerrorList">
										<view :key="item.path" class="errUploadImage"
											@click.native="reloadUpload(index)">
											<image :src="item.path"></image>
										</view>
									</template>
								</view>

							</view>
						</view>
						<view class="fileUpload" v-else>
							<view class="fileUploadList">
								<template v-for="(item,index) in imageValue">
									<view :key="item" class="errUploadImage">
										<image :src="item"></image>
									</view>
								</template><template v-for="(item,index) in pathValue">
									<view :key="item" class="errUploadImage">
										<image :src="item.path"></image>
									</view>
								</template>
								<view class="reloadjiahao" @click="tianjiaImage">
									<image src="/static/jiahao.png" mode=""></image>
								</view>
							</view>

						</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item>
				<button type="primary" :disabled="isLoading" @click="submit" class="w100" :loading="isLoading">
					提交
				</button>
			</uni-forms-item>

		</uni-forms>
	</view>
</template>

<script>
	import tag from "@/components/tag/index.vue";
	export default {
		components: {
			tag,
		},
		data() {
			return {
				reload: false,
				isReloadHaveImg: true,
				isReload: false,
				projectid: 0,
				errImageLoading: false,
				isUploadSomeError: false,
				projectId: 0,
				fileerrorList: [],
				pathValue: [],
				imageValue: [],
				isLoading: false,
				reportrange: ["", ""],
				startrange: ["", ""],
				formData: {
					projectStartTime: "",
					projectEndTime: "",
					briefly: "测试筛选时间3",
					connectPublisher: "13307598394",
					content: "测试筛选时间3",
					createDepartment: "",
					endTime: "",
					enterWay: "测试筛选时间3",
					place: "测试筛选时间3",
					projectName: "测试筛选时间3",
					reward: "测试筛选时间3",
					rule: "测试筛选时间3",
					startTime: "",
					type: '1',
					instituteType: '2'
				},
				type: [{
						text: "理科",
						value: '1',
					},
					{
						text: "文科",
						value: '0',
					},
					{
						text: "不限",
						value: '2',
					},
				],
				dataTree: [],
			};
		},
		methods: {
			tianjiaImage() {
				console.log(this.imageValue.length, 176);
				if (this.imageValue.length === 9) {
					this.$errMessageToast('最多为9张图片')
					return
				}
				console.log(this.pathValue.length, 182);
				console.log(this.imageValue.length + this.pathValue.length, 183);
				if (this.imageValue.length + this.pathValue.length >= 9) {
					this.$errMessageToast('最多为9张图片')
					return
				}
				//更新剩余张数
				this.surplusUploadImages = 9 - this.imageValue.length - this.pathValue.length
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						console.log(!(res.tempFilePaths.length <= this.surplusUploadImages), 194);
						if (!(res.tempFilePaths.length <= this.surplusUploadImages)) {
							//小于等于剩余上传张数
							const count = this.surplusUploadImages
							this.$errMessageToast(`最多只能传${count}张`)
							return
						}


						const tempFilePaths = res.tempFilePaths
						for (let i = 0; i < tempFilePaths.length; i++) {
							this.pathValue.push({
								path: tempFilePaths[i],
								done: true
							});
						}
						console.log(this.pathValue, 210);
					}
				});
			},
			reloadUpload(index) {

				if (this.errImageLoading) return
				console.log(index);
				this.errImageLoading = true
				const path = this.fileerrorList[index].path
				console.log(path, 135);
				uni.uploadFile({
					url: "https://513309q9o0.zicp.fun" + this.$api.uploadFile, //仅为示例，非真实的接口地址
					filePath: path,
					name: "file",
					header: this.$aplsFormDataheader,
					formData: {
						projectId: this.projectId,
					},
					success: (res) => {
						this.errImageLoading = false
						const result = JSON.parse(res.data);
						console.log(result, 146);
						if (result.code != 200) {
							this.$errMessageToast(result.msg)
							return
						}
						this.$nextTick(() => {
							this.fileerrorList.slice(index, 1)

						})

					},
					fail: (eee) => {
						this.errImageLoading = false
						this.$errMessageToast('上传失败，请查看')
					},
				});
			},
			fail(e) {
				this.$errMessageToast(e.errMsg || e);
			},
			returnimageUpload(path, i) {

				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: "https://513309q9o0.zicp.fun" + this.$api.uploadFile, //仅为示例，非真实的接口地址
						filePath: path,
						name: "file",
						header: this.$aplsFormDataheader,
						formData: {
							projectId: this.projectId,
						},
						success: (res) => {
							const result = JSON.parse(res.data);


							if (result.code != 200) {

								this.pathValue[i].done = false


								reject('错误')

								return
							}
							const imgUrl = result.data
							if (!imgUrl) {
								reject('')
								return
							}

							resolve(imgUrl)
						},
						fail: (eee) => {
							reject('上传失败')
							this.$errMessageToast('上传失败，请查看')
						},
					});
				})
			},
			success(e) {},
			select(e) {
				console.log("上传成功");
				console.log(e, 125);
				const tempFiles = e.tempFiles
				for (let i = 0; i < tempFiles.length; i++) {
					this.pathValue.push({
						path: e.tempFiles[i].path,
						done: true
					});
				}


			},
			reportchange(e) {
				this.formData.startTime = e[0];
				this.formData.endTime = e[1];
			},
			startchange(e) {
				this.formData.projectStartTime = e[0];
				this.formData.projectEndTime = e[1];
			},
			timestampToTime(timestamp) {
				var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var Y = date.getFullYear() + "-";
				var M =
					(date.getMonth() + 1 < 10 ?
						"0" + (date.getMonth() + 1) :
						date.getMonth() + 1) + "-";
				var D = date.getDate() + " ";
				return Y + M + D;
			},
			onchange(e) {
				console.log(e);
				this.formData.createDepartment = e.detail.value[0].text;
			},
			vaildType() {
				if (
					this.formData.projectName == "" ||
					this.formData.projectName == undefined
				) {
					throw new Error("请填写比赛名称");
				}
				if (
					this.formData.connectPublisher == "" ||
					this.formData.connectPublisher == undefined
				) {
					throw new Error("请填写联系手机");
				}
				if (!/^1[3456789]\d{9}$/.test(this.formData.connectPublisher)) {
					throw new Error("手机号码有误，请重填");
				}
				if (
					this.formData.startTime == "" ||
					this.formData.startTime == undefined
				) {
					throw new Error("请选择报名开始时间");
				}
				if (this.formData.endTime == "" || this.formData.endTime == undefined) {
					throw new Error("请选择报名截止时间");
				}
				if (
					this.formData.projectStartTime == "" ||
					this.formData.projectStartTime == undefined
				) {
					throw new Error("请选择举办时间");
				}
				if (
					this.formData.projectEndTime == "" ||
					this.formData.projectEndTime == undefined
				) {
					throw new Error("请选择结束时间");
				}
				if (
					new Date(this.formData.startTime).getTime() >
					new Date(this.formData.projectStartTime).getTime()
				) {
					throw new Error("报名开始日期不能大于举办开始日期");
				}
				if (
					new Date(this.formData.startTime).getTime() ==
					new Date(this.formData.projectStartTime).getTime()
				) {
					throw new Error("报名开始日期不可以和举办开始同一天");
				}
				if (
					new Date(this.formData.endTime).getTime() >
					new Date(this.formData.projectEndTime).getTime()
				) {
					throw new Error("报名截止日期不能大于举办结束日期");
				}
				if (
					new Date(this.formData.endTime).getTime() >=
					new Date(this.formData.projectStartTime).getTime()
				) {
					throw new Error("报名截止日期不能大于等于举办开始日期");
				}
				if (this.formData.place == "" || this.formData.place == undefined) {
					throw new Error("请填写比赛地点");
				}
				if (
					this.formData.createDepartment == "" ||
					this.formData.createDepartment == undefined
				) {
					throw new Error("请选择发起组织");
				}
				if (this.formData.briefly == "" || this.formData.briefly == undefined) {
					throw new Error("请填写比赛简介");
				}
				if (this.formData.content == "" || this.formData.content == undefined) {
					throw new Error("请填写比赛内容");
				}
				if (this.formData.rule == "" || this.formData.rule == undefined) {
					throw new Error("请填写比赛规则");
				}
				if (this.formData.reward == "" || this.formData.reward == undefined) {
					throw new Error("请填写比赛奖励");
				}
				if (this.formData.enterWay == "" || this.formData.enterWay == undefined) {
					throw new Error("请填写比赛加入方式或者填无");
				}
				return true;
			},
			handleUploadImage() {
				//遍历数组，查看错误位置
				this.isUploadSomeError = true
				const list = this.pathValue
				console.log(list, 296);
				const errIndexList = list.map(item => {
					console.log(item.done, 298);
					if (!item.done) {
						return {
							done: false,
							path: item.path
						}
					}

				})
				console.log(errIndexList, 'errIndexList');
				this.fileerrorList = errIndexList
				uni.hideLoading();
				uni.showToast({
					title: '发布成功，但存在图片上传失败',
					duration: 2000,
					icon: 'none'
				})

			},
			async submit() {
				
				try {
					if (this.vaildType()) {
						let data
						if (this.reload) {
							data = {
								...this.formData,
								projectId: this.projectId
							}
						} else {
							data = {
								...this.formData
							}
						}
						console.log(data, 447);

						this.isLoading = true;
						const result = await this.$mjcrequest.request({
							url: this.$api.addProject,
							data: JSON.stringify(data),
							header: this.$aplsjsonheader,
							isToast: true,
						});
						
						if (this.pathValue.length == 0) {
							this.reload ? this.$setTimeoutback('reload') : this.$setTimeoutback()
							return
						}
						uni.showLoading({
							title: '正在上传图片'
						})
						this.projectId = result.project.projectId

						if (this.pathValue.length == 0) return
						//文件遍历上传

						const promiseList = []
						const files = this.pathValue


						for (let i = 0; i < files.length; i++) {

							const path = files[i].path
							const item = this.returnimageUpload(path, i)

							promiseList.push(item)
						}



						Promise.allSettled(promiseList).then(res => {
							const isErrorSome = res.some(item => {
								return item.status != 'fulfilled'
							})
							console.log(isErrorSome, 'isErrorSome');
							uni.hideLoading();
							if (isErrorSome) {
								//存在失败
								this.handleUploadImage()
								return
							}

							uni.showToast({
								title: '所有信息上传成功，等待审核',
								icon: 'none',
								duration: 1100
							})
							this.reload ? this.$setTimeoutback('reload') : this.$setTimeoutback()
						})
					}
				} catch (errMessage) {
					console.log(errMessage, 'errMessage');
					this.isLoading = false;
					//TODO handle the exception
					this.$errMessageToast(errMessage.message || errMessage);
				}
			},
		},
		onLoad(options) {
			const {
				reload
			} = options
			if (reload) {
				this.$eventBus.$on('editProjectMsg', (editItem) => {
					console.log(editItem, 'editprojectItem')
					this.reload = true //代表回显标识符
					this.formData.projectStartTime = editItem.projectStartTime
					this.formData.projectEndTime = editItem.projectEndTime
					this.formData.briefly = editItem.briefly
					this.formData.connectPublisher = editItem.connectPublisher
					this.formData.content = editItem.content
					this.formData.createDepartment = editItem.createDepartment
					this.formData.endTime = editItem.endTime
					this.formData.enterWay = editItem.enterWay
					this.formData.place = editItem.place
					this.formData.projectName = editItem.projectName
					this.formData.reward = editItem.reward
					this.formData.rule = editItem.rule
					this.formData.startTime = editItem.startTime
					this.formData.instituteType = editItem.instituteType.toString()
					this.projectId = editItem.projectId
					//
					this.reportrange = [editItem.startTime, editItem.endTime]
					this.startrange = [editItem.projectStartTime, editItem.projectEndTime]
					this.dataTree[0] = editItem.createDepartment
					if (editItem.imgUrl.length == 0 || !editItem.imgUrl) {
						//没有上传图片数据，显示uniapp组件
						this.isReloadHaveImg = false
					} else {
						this.imageValue = editItem.imgUrl
					}
				})
			}
		},
		mounted() {
			console.log('我是编辑比赛，我mouted');
			this.$eventBus.$emit('sendProjectEditMsg')
		},
		destroyed() {
			console.log('beforeDestroy')
			this.$eventBus.$off('editProjectMsg')
		},
		async created() {
			const data = {
				pageNum: 1,
				pageSize: 100,
			};

			const nel = uni.getStorageSync("newList");
			if (!nel) {
				const result = await this.$mjcrequest.request({
					url: this.$api.getInstituteDic,
					data: JSON.stringify(data),
					header: this.$aplsjsonheader,
				});
				console.log(result);
				const newList = result.pageDate.map((item) => {
					return {
						text: item.instituteName,
						value: item.instituteName,
						instituteId: item.instituteId,
					};
				});
				uni.setStorageSync("newList", newList);
				this.dataTree = nel;
			} else {
				this.dataTree = nel;
			}
		},
	};
</script>

<style lang="less">
	.addProject {
		height: auto;
		padding: 10rpx 20rpx 15rpx 20rpx;
		background-color: #fff;

		.tagsList {
			max-width: calc(100% - 25rpx) !important;
			width: auto;
		}


		.fileUpload {
			display: flex;
			flex-direction: column;
			flex-wrap: wrap;

			& .fileUploadList {
				display: flex;
				flex-wrap: wrap;

				& .reloadjiahao {


					& image {
						width: 100rpx;
						height: 100rpx
					}
				}

				& .errUploadImage {
					border-radius: 50%;
					overflow: hidden;



					& image {
						width: 100rpx;
						height: 100rpx;
						border-radius: 50%;
						overflow: hidden;
					}
				}

			}
		}

		.jiahao {
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			overflow: hidden;

			& image {
				width: 100%;
				height: 100%;
			}
		}

		.uni-forms-item__content {
			display: flex;
			align-items: center;
		}

		.w100 {
			width: 100%;
		}
	}
</style>
